/*
 * @Autor: Shihh
 * @Description: 
 * @Version: 1.0
 * @Date: 2020-05-07 15:30:55
 */
const Sequelize = require('sequelize')
const log4js = require('../config/log4js').log4js
const logger = log4js.getLogger('special-topics');

module.exports = (sequelize, DataTypes) => {

  class specialTopic extends Sequelize.Model {

    /**
     * @author: Shihh
     * @description: 获取热门专题
     * @param {type} 
     * @return: 
     */
    static getHotTopics(pars) {
      var querydata = []
      var [page = 1, pagesize = 15, limit = 0] = [pars.page, pars.pagesize, pars.limit]
      let condition = {
        attributes: ['id', 'name', 'thumbnail', 'status', 'sort', 'create_time', 'link_type','link_name', 'link_id', 'link'],
        raw: true,
        offset: pagesize * (page - 1),
        limit: parseInt(pagesize)
      }
      if(pars.where!==undefined&&pars.where!==null)
      condition.where = pars.where;
      condition.order = [
        ['sort', 'ASC']
      ]
      querydata = this.findAll(condition)
      return querydata;
    }

    /**
     * @author: Shihh
     * @description: 新增热门专题
     * @param {type} 
     * @return: 
     */
    static async addHotTopics(form) {
      let create_time = parseInt(new Date().getTime() / 1000);
      let obj = {
        name: form.name,
        thumbnail: form.thumbnail,
        status: form.status,
        sort: form.sort,
        create_time: create_time,
        link_type: form.link_type,
        link: form.link
      }
      if( form.link_type !== 4 ){
        obj.link_id = form.link_id
        obj.link_name = form.link_name
      }
      return await this.create(obj).then(re => {
        return true
      }).catch(err => {
        logger.error(err)
        return false
      })
    }
    /**
     * @author: Shihh
     * @description: 编辑专题
     * @param {type} 
     * @return: 
     */
    static async editHotTopics(form) {
      let obj = {
        name: form.name,
        thumbnail: form.thumbnail,
        status: form.status,
        sort: form.sort,
        link_type: form.link_type,
        link: form.link,
        link_name: form.link_name,
        link_id: form.link_id == '' ? null : form.link_id
      }
      return await this.update(obj, { 'where': { 'id': form.id } }).then(re => {
        return true
      }).catch(err => {
        logger.error(err)
        return false
      })
    }

    /**
     * @author: Shihh
     * @description: 删除热门
     * @param {type} 
     * @return: 
     */
    static async deleteTopic(pars) {
      return await this.destroy({
        where: {
          id: pars.id,
        },
      }).then(re => {
        return true
      }).catch(err => {
        return false
      })
    }
    /**
     * @author: Shihh
     * @description: 通过id或name搜索专题
     * @param {type} 
     * @return: 
     */
    static async getTagByIdOrName(params) {
      let querydata = []
      querydata = await this.findAll({ where: { [Op.or]: [{ name: { [Op.like]: `%${params}%` } }, { id: params }] } })
      return querydata
    }

    /**
     * @author: Shihh
     * @description: 获取列表条数，用于添加排序
     * @param {type} 
     * @return: 
     */
    static getHotCount() {
      return this.count();
    }

    /**
     * @author: Shihh
     * @description: 拽动排序 待ctrl修改完改动
     * @param {type} 
     * @return: 
     */    
    static async hotSort(params) {
      var queryData = []
      var valueArr = []
      // let sql = `select id,sort from special_topic order by sort asc`
      // queryData = await this.raw(sql)
      queryData=await this.findAll({attributes:['id','sort'],order:[['sort', 'ASC']]})
      //start拖动的目的地
      //end从哪一行开始拖动的
      //start《end从后往前拖动   start》end从前往后拖动
      if (parseInt(params.start) < parseInt(params.end)) {//从后往前拖动
          for (var i = parseInt(params.start); i <= parseInt(params.end); i++) {
              //console.log(i == parseInt(params.end))
              if (i == parseInt(params.end)) {
                  var value = {
                      id: queryData[i].id,
                      sort: parseInt(params.start) + 1
                  };
              } else {
                  var value = {
                      id: queryData[i].id,
                      sort: queryData[i].sort + 1,
                  };
              }

              valueArr.push(value)
          }
      } else if (parseInt(params.start) > parseInt(params.end)) {//从前往后拖动
          for (var i = parseInt(params.end); i <= parseInt(params.start); i++) {
              if (i == parseInt(params.end)) {
                  var value = {
                      id: queryData[i].id,
                      sort: parseInt(params.start) + 1
                  }
              } else {
                  var value = {
                      id: queryData[i].id,
                      sort: queryData[i].sort - 1,
                  };
              }

              valueArr.push(value)
          }
      }
      var updateData = []
      updateData = await this.bulkCreate(valueArr, { updateOnDuplicate: ["sort"] });
      return updateData
  }

  static async getSpecialById(id){
    let banner=await this.findOne({where:{id},raw:true})
    return banner;
  }

   
   /**
    * @author: xgq
    * @description: 修改专题状态
    * @param {type} 
    * @return: 
    */   
   static async modifyStatus(pars){
    let {id,status}=pars;
    let result = await this.update({status},{where:{id}})
    return result;
  }

  }

  specialTopic.init({
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    name: { type: DataTypes.STRING(45) },
    sort: { type: DataTypes.INTEGER },
    status: { type: DataTypes.INTEGER, defaultValue: 0 },
    link: { type: DataTypes.STRING(255) },
    link_id: { type: DataTypes.INTEGER },
    link_name: { type: DataTypes.STRING(45) },
    link_type: { type: DataTypes.INTEGER },
    create_time: { type: DataTypes.INTEGER },
    thumbnail: { type: DataTypes.STRING(255) }
  }, {
    sequelize,
    modelName: 'special_topic',
    freezeTableName: true,
    timestamps: false
  });

  return specialTopic;
}